package com.hope;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

//测试反射调用的性能，优化
public class Reflection02 {

    public static void main(String[] args) throws Exception{
        m1();
        m2();
        m3();
    }


    //普通方法调用hi
    public static void m1() {
        Cat cat = new Cat();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            cat.hi();
        }
        long end = System.currentTimeMillis();
        System.out.println("传统方法来调用hi() 耗时:" + (end - start));
    }

    //反射机制调用hi
    public static void m2() throws Exception {
        Class cls = Class.forName("com.hope.Cat");
        Object o = cls.getDeclaredConstructor().newInstance();
        Method hi = cls.getMethod("hi");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            hi.invoke(o);

        }
        long end = System.currentTimeMillis();
        System.out.println("反射方法来调用hi() 耗时:" + (end - start));
    }
    public static void m3() throws Exception {
        Class cls = Class.forName("com.hope.Cat");
        Object o = cls.getDeclaredConstructor().newInstance();
        Method hi = cls.getMethod("hi");
        hi.setAccessible(true);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            hi.invoke(o);

        }
        long end = System.currentTimeMillis();
        System.out.println("反射方法来调用hi() 耗时:" + (end - start));
    }


}
